<!--
author:        hejy <silentmanager@163.com>
date:          2024-11-07 19:00:54
component:     setMenu
Copyright © YourCompanyName All rights reserved
-->

<template>
  <el-dialog title="套餐列表" v-model="isVisible" @close="handleClose" width="1200px">
    <FormComponent :inline="true" ref="formRef" :config="formConfig" />
    <div
      style="
        display: flex;
        align-items: center;
        flex-direction: row;
        margin-left: 36px;
        margin-bottom: 24px;
      "
    >
      <el-button @click="handleQuery">搜索</el-button>
      <el-button @click="resetQuery">重置</el-button>
      <el-button type="warning" @click="handleSubmit">提交</el-button>
    </div>
    <div>
      <el-tabs v-model="activeName" type="card" class="demo-tabs">
        <el-tab-pane label="常规套餐" name="first">
          <el-alert :title="'已选择 ' + selectedCount + ' 项'" type="success" />
          <el-table
            ref="tableRef"
            v-loading="loading"
            :row-key="getRowKey"
            @selection-change="handleSelectionChange"
            :data="list"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" :reserve-selection="true" />
            <el-table-column label="商品编号" prop="packageCode" />
            <el-table-column label="套餐名称" prop="packageName" />
            <el-table-column label="价格" prop="price" />
            <el-table-column label="瓶数" prop="bottleCount" />
            <el-table-column label="箱数" prop="packageCount" />
            <el-table-column label="奖金" prop="bonusRule" />
            <el-table-column label="套餐商品和可用库存" prop="packageContent">
              <template #default="scope">
                <span
                  class="drink_content"
                  v-for="(item, index) in scope.row.packageContentList"
                  :key="index"
                >
                  <span>
                    {{ item.drinkName }}
                  </span>
                  <span> ({{ item.bottleCount }} &times; {{ item.num }}) </span>
                  <span> &times; {{ item.packageCount }} </span>
                  [<span :class="item.stock > -1 ? 'inventory' : 'no_inventory'">{{
                    item.stock
                  }}</span
                  >]
                  <span v-if="index !== scope.row.packageContentList.length - 1">,</span>
                </span>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <Pagination
            :total="total"
            v-model:page="queryParams.pageNo"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </el-tab-pane> </el-tabs
    ></div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { pagePackageManagement, PagePackageManagementRes } from '@/api/drinks/set-menu'
import { ref, watch, defineProps, defineEmits } from 'vue'
import FormComponent from '@/components/FormComponent/index.vue'
import { TableDataModel } from '../index.vue'
import { ElTable } from 'element-plus'

interface Props {
  visible: boolean
  tableData: TableDataModel[]
}
const props = defineProps<Props>()
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'update-data', data: TableDataModel[]): void
}>()

// --------------------  tab  ---------------------
const activeName = ref('first')

// --------------------  表单  ---------------------
const formRef = ref<InstanceType<typeof FormComponent>>()
const formConfig = [
  {
    label: '商品编码',
    prop: 'packageCode',
    type: 'input',
    options: { placeholder: '请输入商品编码' }
  },
  {
    label: '套餐名称',
    prop: 'packageName',
    type: 'input',
    options: { placeholder: '请输入套餐名称' }
  },
  {
    label: '套餐价格',
    prop: 'price',
    type: 'input',
    options: { placeholder: '请输入套餐价格' }
  }
]
// --------------------  表格  ---------------------
const tableRef = ref<InstanceType<typeof ElTable>>()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref<PagePackageManagementRes[]>([]) // 列表的数据
// 分页
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10
})
// 定义选中项数量的状态
const selectedCount = ref(0)

const selectList = ref<TableDataModel[]>([])

// 处理选择变化的函数
const handleSelectionChange = (selection: PagePackageManagementRes[]) => {
  const newSelectList = selection.map((item) => {
    const oldData = props.tableData.find((it) => it.packageId === item.id)
    return {
      bottleCount: 0,
      num: oldData?.num || 1,
      packageCount: 0,
      packageId: item.id,
      packagePrice: item.price,
      packageTotal: 0,
      packageTurnover: item.packageRevenue,
      pendingPayment: 0,
      prepayment: oldData?.prepayment || 0,
      shippingExtra: oldData?.shippingExtra || 0,
      packageExtra: oldData?.packageExtra || 0,
      packageName: item.packageName,
      packageRevenue: item.packageRevenue,
      originBottleCount: item.bottleCount,
      originPackageCount: item.packageCount
    }
  })
  selectList.value = newSelectList
  selectedCount.value = selection.length // 更新选中项的数量
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await pagePackageManagement({
      ...queryParams,
      ...formRef.value?.formData,
      isListed: true
    })
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}
onMounted(() => {
  getList()
})

const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const resetQuery = () => {
  formRef.value?.handleReset()
  handleQuery()
}

const handleSubmit = () => {
  handleClose()
  emit('update-data', selectList.value)
}

const getRowKey = (row: any) => {
  return row.id
}

const isVisible = ref<boolean>(props.visible)
// --------------------  弹窗状态  ---------------------

// 监视 props.visible 的变化，以更新局部状态
watch(
  () => props.visible,
  (newValue) => {
    isVisible.value = newValue
    if (newValue) {
      tableRef?.value?.clearSelection()
    }
  }
)

watch(
  [() => props.visible, () => props.tableData, () => list],
  ([newVisible, newTableData, newList]) => {
    if (newVisible) {
      selectList.value = props.tableData
      const filteredArray = newList.value.filter((item) =>
        newTableData.some((el) => el.packageId === item.id)
      )
      filteredArray.forEach((item) => {
        tableRef?.value?.toggleRowSelection(item, true)
      })
    }
  }
)

// 关闭弹窗的处理函数
const handleClose = () => {
  isVisible.value = false // 设置局部状态
  emit('update:visible', false) // 通知父组件
}
</script>

<style scoped lang="scss">
::v-deep(.el-table__header-wrapper th .cell) {
  font-size: 14px;
  font-weight: bold;
  color: #333;
}

.drink_content {
  & > span:nth-child(4) {
    &.inventory {
      color: green;
    }
    &.no_inventory {
      color: red;
    }
  }
}
</style>
